package com.stillalive.springbootbooksystem.Controller;

import com.stillalive.springbootbooksystem.Model.*;
import com.stillalive.springbootbooksystem.Service.BookService;

import com.stillalive.springbootbooksystem.enums.BookStatusEnum;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
@Slf4j
// 表现层
@RestController
@RequestMapping("/book")
public class BookController {

    // 这里注解表示从Spring中获取bookService对象
    @Autowired
    private BookService bookService;

    @RequestMapping(value = "/addBook", produces = "application/json")
    public String addBook(BookInfo bookInfo) {
        // 这里{}相当于一个占位符，打印时会把失败的bookInfo打印出来
        log.info("添加图书，request:{}"+ bookInfo);
        if (!StringUtils.hasText(bookInfo.getBookName())) {
            return "书名不能为空";
        }
        if (bookInfo.getBookName().length() > 100) {
            return "书名长度不能超过100个字符";
        }
        if (!StringUtils.hasText(bookInfo.getAuthor())) {
            return "作者不能为空";
        }
        if (bookInfo.getAuthor().length() > 50) {
            return "作者姓名长度不能超过50个字符";
        }
        if (!StringUtils.hasText(bookInfo.getPublish())) {
            return "出版社不能为空";
        }
        if (bookInfo.getPublish().length() > 100) {
            return "出版社名称长度不能超过100个字符";
        }
        if (bookInfo.getCount() == null || bookInfo.getCount() <= 0) {
            return "库存数量必须大于0";
        }
        if (bookInfo.getPrice() == null || bookInfo.getPrice().doubleValue() <= 0) {
            return "价格必须为正数";
        }
        if (bookInfo.getStatus() == null) {
            return "图书状态不能为空";
        }
        // 状态只能是 1（正常）或 2（不允许借阅）
        if (bookInfo.getStatus() != 1 && bookInfo.getStatus() != 2) {
            return "图书状态值不合法";
        }

        try{
            bookService.addBook(bookInfo);
            return "";
        }catch (Exception e){
            log.warn(e.getMessage());
            return "添加图书发生异常";
        }
    }

    @RequestMapping(value = "/getListByPage", produces = "application/json")
    public Result<ResponseResult<BookInfo>> getListByPage(PageRequest pageRequest) {
        ResponseResult<BookInfo>listByPage = bookService.getListByPage(pageRequest);
        return Result.success(listByPage);
    }

    @RequestMapping( value = "/queryBookById", produces = "application/json")
    public BookInfo queryBookById(Integer bookId) {
        log.info("查询图书信息，bookId:" +  bookId);
        return bookService.queryBookById(bookId);
    }

    @RequestMapping(value = "/updateBook", produces = "application/json")
    public String updateBook(BookInfo bookInfo) {
        log.info("修改图书, bookInfo:{}" + bookInfo);
        
        // 参数验证
        if (bookInfo.getId() == null || bookInfo.getId() <= 0) {
            return "图书ID不能为空";
        }
        if (!StringUtils.hasText(bookInfo.getBookName())) {
            return "书名不能为空";
        }
        if (bookInfo.getBookName().length() > 100) {
            return "书名长度不能超过100个字符";
        }
        if (!StringUtils.hasText(bookInfo.getAuthor())) {
            return "作者不能为空";
        }
        if (bookInfo.getAuthor().length() > 50) {
            return "作者姓名长度不能超过50个字符";
        }
        if (!StringUtils.hasText(bookInfo.getPublish())) {
            return "出版社不能为空";
        }
        if (bookInfo.getPublish().length() > 100) {
            return "出版社名称长度不能超过100个字符";
        }
        if (bookInfo.getCount() == null || bookInfo.getCount() <= 0) {
            return "库存数量必须大于0";
        }
        if (bookInfo.getPrice() == null || bookInfo.getPrice().doubleValue() <= 0) {
            return "价格必须为正数";
        }
        if (bookInfo.getStatus() == null) {
            return "图书状态不能为空";
        }
        // 状态只能是 1（正常）或 2（不允许借阅）
        if (bookInfo.getStatus() != 1 && bookInfo.getStatus() != 2) {
            return "图书状态值不合法";
        }
        
        try{
            bookService.updateBook(bookInfo);
            return "";
        }catch (Exception e){
            log.error("修改图书发生异常，e:" + e);
            return "修改图书发生异常";
        }
    }

    @RequestMapping("/deleteBook")
    public Result<String> deleteBook(Integer bookId, HttpSession session) {
        log.info("删除图书,bookId:{}" + bookId);
        
        if(bookId == null || bookId <= 0){
            return Result.fail("图书ID不能为空", null);
        }
        
        try{
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(bookId);
            // 图书状态改为已删除
            bookInfo.setStatus(BookStatusEnum.DELETE.getCode());
            bookService.updateBook(bookInfo);
            return Result.success("");
        }catch (Exception e){
            log.error("删除图书发生异常，e:" + e);
            return Result.fail("删除图书发生异常", null);
        }
    }

    @RequestMapping("/batchDelete")
    public Result<String> batchDelete(@RequestParam("ids") List<Integer> bookIds, HttpSession session) {
        log.info("批量删除图书，bookIds:" + bookIds);
        try {
            if (bookIds == null || bookIds.isEmpty()) {
                log.warn("批量删除图书参数为空");
                return Result.fail("请选择要删除的图书", null);
            }
            Integer result = bookService.batchDelete(bookIds);
            log.info("批量删除影响行数: " + result);
            if(result != null && result > 0){
                return Result.success("");
            } else {
                return Result.fail("批量删除失败", null);
            }
        } catch (Exception e) {
            log.error("批量删除图书失败, e:" + e);
            return Result.fail("批量删除图书发生异常", null);
        }
    }
}
